package vip.xiaomoli.nurse.util;

import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class ApplicationContextHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHelper.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name) {
        if (null != applicationContext) {
            //noinspection unchecked
            return (T) applicationContext.getBean(name);
        }
        return null;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (null != applicationContext) return applicationContext.getBean(clazz);
        return null;
    }

    public static String[] getBeanNamesForType(Class<?> clazz) {
        if (null != applicationContext) return applicationContext.getBeanNamesForType(clazz);
        return null;
    }

    public static <T> T getDubboBean(Class<T> clazz) {
        ReferenceAnnotationBeanPostProcessor dubboContext = applicationContext.getBean(ReferenceAnnotationBeanPostProcessor.class);
        Collection<ReferenceBean<?>> referenceBeans = dubboContext.getReferenceBeans();
        for (ReferenceBean<?> referenceBean : referenceBeans) {
            Class<?> objectType = referenceBean.getObjectType();
            if (objectType == clazz) {
                //noinspection unchecked
                return (T) referenceBean.getObject();
            }
        }
        return null;
    }

    public static <T> T getSpringOrDubboBean(Class<T> clazz) {
        T bean = ApplicationContextHelper.getBean(clazz);
        if (null == bean) bean = ApplicationContextHelper.getDubboBean(clazz);
        return bean;
    }

}
